<template>
  <div class="system-info">
    <div class="wrapper-title">{{ $t('发布公告') }}</div>
    <div class="anno-form">
      <div class="label">{{ $t('发布内容') }}</div>
      <el-input v-model="annoContent" resize="none" style="width: calc(100vw - 554px)" type="textarea" :autosize="false"
                :placeholder="$t('请输入发布内容')" />
    </div>
    <div class="submit">
      <el-button type="primary" size="large" @click="handleSubmit">{{ $t('提交') }}</el-button>
    </div>
    <div class="history">
      <div class="label-out">{{ $t('历史公告') }}</div>
      <el-button type="primary" plain :icon="Delete" style="margin-bottom: 20px" @click="deleteSome">{{ $t('删除') }}</el-button>
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column property="annoContent" :label="$t('公告内容')" />
        <el-table-column property="publishTime" :label="$t('发布时间')" />
        <el-table-column :label="$t('操作')" width="100">
          <template #default="scope">
            <div class="actions">
              <span class="iconfont icon-shanchu" @click="deleteItem(scope.row.id)"></span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination" v-if="total > 0">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                       :page-sizes="[100, 200, 300, 400]" :size="size" :disabled="disabled" :background="background"
                       layout="prev, pager, next" :total="total" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange" />
        <span class="total">{{ $t('共') }}{{ total }}{{ $t('条') }}</span>
      </div>
    </div>
  </div>
</template>

<script>
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Delete } from '@element-plus/icons-vue';
  import Tab from '@/components/tab';
  import { announcementPage, addAnnouncement, deleteAnnouncement } from '@/api/index';

  export default {
    props: {},
    components: { Tab },
    data() {
      return {
        Delete,
        annoContent: '',
        total: null,
        currentPage: 1,
        pageSize: 20,
        size: 'default',
        disabled: false,
        background: true,
        selections: [],
        tableData: [],
        selectedItems: []
      };
    },
    methods: {
      handleSelectionChange(selectedItems) {
        this.selectedItems = selectedItems;
      },
      // 获取公告数据
      async fetchData() {
        const params = {
          page: this.currentPage,
          count: this.pageSize,
        };
        try {
          const { data } = await announcementPage({ ...params }); // 使用封装的 API 请求方法
          if (data.code === 0) {
            this.tableData = data.data.records; // 更新表格数据
            this.total = +data.data.total; // 更新总数据条数
            this.pageSize = +data.data.size; // 设置每页条数
          }
        } catch (error) {
          console.log(error);
        }
      },
      // 新增
      async handleSubmit() {
        if (!this.annoContent) {
          ElMessage.error(this.$t('发布内容不能为空'));
          return;
        }
        try {
          const { data } = await addAnnouncement({
            annoContent: this.annoContent,
          });
          if (data.code === 0) {
            this.fetchData();
            ElMessage.success(this.$t('公告添加成功'));
            this.annoContent = '';
          }
        } catch (error) {
          console.log(error);
        }
      },
      deleteItem(id) {
        ElMessageBox.confirm(
            this.$t('删除该公告后不能恢复，确定要删除吗？'),
            this.$t('删除确认'),
            {
              confirmButtonText: this.$t('删除'),
              cancelButtonText: this.$t('取消'),
              type: 'warning',
            },
        )
            .then(async () => {
              try {
                const { data } = await deleteAnnouncement([id]); // 使用数组传递单个 ID
                if (data.code === 0) {
                  ElMessage({
                    type: 'success',
                    message: this.$t('删除成功'),
                  });
                  this.fetchData(); // 删除后刷新数据
                } else {
                  ElMessage({
                    type: 'error',
                    message: data.message || this.$t('删除失败，请重新操作'),
                  });
                }
              } catch (error) {
                console.log(error);
                ElMessage({
                  type: 'error',
                  message: this.$t('删除请求失败，请稍后再试'),
                });
              }
            })
            .catch(() => {
              ElMessage({
                type: 'info',
                message: this.$t('取消删除'),
              });
            });
      },
      deleteSome() {
        const selectedIds = this.selectedItems.map(
            (item) => item.id,
        );

        if (selectedIds.length === 0) {
          ElMessage({
            type: 'warning',
            message: this.$t('请选择要删除的公告！'),
          });
          return;
        }

        ElMessageBox.confirm(
            this.$t('已选择') + ' ' + selectedIds.length + ' ' +  this.$t('条公告数据，删除该公告后不能恢复，确定要删除吗？'),
            this.$t('删除确认'),
            {
              confirmButtonText: this.$t('删除'),
              cancelButtonText: this.$t('取消'),
              type: 'warning',
            },
        )
            .then(async () => {
              try {
                const { data } = await deleteAnnouncement(selectedIds); // 使用数组传递多个 ID
                if (data.code === 0) {
                  ElMessage({
                    type: 'success',
                    message: this.$t('删除成功'),
                  });
                  this.fetchData(); // 删除后刷新数据
                } else {
                  ElMessage({
                    type: 'error',
                    message: data.message || this.$t('删除失败，请重新操作'),
                  });
                }
              } catch (error) {
                console.log(error);
                ElMessage({
                  type: 'error',
                  message: this.$t('删除请求失败，请稍后再试'),
                });
              }
            })
            .catch(() => {
              ElMessage({
                type: 'info',
                message: this.$t('取消删除'),
              });
            });
      },
      // 已选项
      selectionChange(selections) {
        this.selections = selections;
      },
      // 翻页处理
      handleCurrentChange(page) {
        this.currentPage = page;
        this.fetchData(); // 翻页时重新请求数据
      },
      // 每页显示条数变化处理
      handleSizeChange(size) {
        this.pageSize = size;
        this.fetchData(); // 每页条数变化时重新请求数据
      },
    },
    mounted() {
      this.fetchData();
    }
  };
</script>

<style lang="scss" scoped>
.system-info {
  margin-top: 20px;

  .submit {
    padding-right: 40px;
    padding-top: 20px;
    text-align: right;
  }

  .history {
    .el-button {
      transition: 0.3s ease;
      background: #303f2e;
      border-color: $color;

      &:hover {
        background-color: $color;
        border-color: $color;
      }
    }
  }

  .wrapper-title {
    font-weight: 500;
    font-size: 24px;
    color: #ffffff;
    line-height: 38px;
    margin-bottom: 20px;
  }

  .actions {
    .iconfont {
      font-size: 20px;
      transition: 0.3s ease;
      margin-right: 26px;
      cursor: pointer;

      &:hover {
        color: $color;
      }
    }
  }

  .anno-form {
    display: flex;
    margin-bottom: 20px;

    .el-input__wrapper {
      border-radius: 10px;
      padding: 10px;
    }

    .label {
      font-weight: 400;
      font-size: 18px;
      color: #ffffff;
      margin-right: 30px;
    }
  }

  .label-out {
    font-weight: 400;
    font-size: 18px;
    color: #ffffff;
    padding: 30px 0 16px;
  }
}
</style>
